import { createStore } from 'vuex';
import { LoginByAccount } from "@/api/user";
import {setToken} from '@/utils/auth'

const store = createStore({
    state() {
        return {
            count: 10000
        }
    },
    actions: {
        LoginByAccount(context, userInfo) {
            const {username, password} = userInfo
            return new Promise((resolve, reject) => {
                LoginByAccount({username: username.trim(), password}).then(response => {
                    console.log(response);
                    const data = response.data

                    context.commit('SET_TOKEN', data.token)
                    setToken(response.data.token);//登录成功后将token存储在 localStorage 之中
                    resolve()
                }).catch(error => {
                    reject(error)
                });
            });
        },
        add(context, value) {
            console.log(context, value);

            context.commit('increment');

            context.dispatch('del', 1);
        },
        del(context, value) {
            console.log('---actions-del', context, value);
            context.commit('decrease', value);
        }
    },
    mutations: {
        SET_TOKEN(state, token) {
            state.token = token
        },
        increment(state) {
            console.log('mutations...');
            state.count++
        },
        decrease(state, value) {
            state.count -= value
        }
    }
})

export default store